package com.appstore.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.appstore.dao.IApplicationDao;
import com.appstore.dao.impl.ApplicationDaoImpl;
import com.appstore.model.Application;
import com.opensymphony.xwork2.ActionSupport;

public class HomeAction extends ActionSupport {

	private IApplicationDao applicationDao;
	private List list;

	public HomeAction() {
		applicationDao = ApplicationDaoImpl.getApplicationDaoImpl();
	}

	@Override
	public String execute() throws Exception {
		this.list = applicationDao.findAll();
		this.list = optApplicationList(this.list);
		return super.execute();
	}

	private List optApplicationList(List list) {
		SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
		SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
		List<List<Application>> appsList = new ArrayList<List<Application>>();
		int size = list.size();
		int index = 0;
		if (size > 0) {
			List<Application> apps = new ArrayList<Application>();
			appsList.add(apps);
		}
		for (int i = 0; i < size; i++) {
			List<Application> apps = appsList.get(index);
			Application app = (Application) list.get(i);
			if (apps.isEmpty()) {
				apps.add(app);
			} else {
				Application temp = apps.get(0);
				if ((yearFormat.format(temp.getUpdatedTime()).equals(yearFormat
				        .format(app.getUpdatedTime())))
				        && (monthFormat.format(temp.getUpdatedTime())
				                .equals(monthFormat.format(app.getUpdatedTime())))) {
					apps.add(app);
				} else {
					index++;
					List<Application> newApps = new ArrayList<Application>();
					newApps.add(app);
					appsList.add(newApps);
				}
			}
		}
		return appsList;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

}
